<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus13.html">Previous Chapter</a>
    <li> <a href="cplusplus15.html">Next Chapter</a>
</ul>
<hr>
<a name="POLYMORPHISM"></a><a name="l198"></a>
<h1>Chapter 14: Polymorphism</h1>
<a name="polymorphism"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="polymorphism/intro"></a>As we have seen in chapter <a href="cplusplus13.html#INHERITANCE">13</a>, <strong>C++</strong> provides the tools to
derive classes from base classes, and to use base class pointers to address
derived objects. As we've also seen, when using a <a name="an1922"></a>
base class pointer to
address an object of a <a name="an1923"></a>
derived class, the type of the pointer determines
which <a name="an1924"></a>
member function will be used. This means that a <code>Vehicle *vp</code>,
pointing to a <code>Truck</code> object, will incorrectly compute the truck's combined
weight in a statement like <code>vp-&gt;weight()</code>. The reason for this should now be
clear: <code>vp</code> calls <code>Vehicle::weight()</code> and not <code>Truck::weight()</code>, even
though <code>vp</code> actually points to a <code>Truck</code>.
<p>
Fortunately, a remedy is available. In <strong>C++</strong> a <code>Vehicle *vp</code> may call a
function <code>Truck::weight()</code> when the pointer actually points to a <code>Truck</code>.
<p>
The terminology for this feature is <a name="an1925"></a>
<em>polymorphism</em>: it is as though the
pointer <code>vp</code> changes its type from a base class pointer to a pointer to the
class of the object it actually points to.  So, <code>vp</code> might behave like a
<code>Truck *</code> when pointing to a <code>Truck</code>, and like an <code>Auto *</code> when pointing
to an <code>Auto</code> etc..&nbsp;(In one of the StarTrek movies, Capt.  Kirk was
in trouble, as usual. He met an extremely beautiful lady who, however,
later on changed into a hideous troll. Kirk was quite surprised, but the lady
told him: ``Didn't you know I am a polymorph?'')
<p>
Polymorphism is realized by a feature called <a name="an1926"></a>
<em>late binding</em>. It's called
that way because the decision <em>which</em> function to call (a base class
function or a function of a derived class) cannot be made <a name="an1927"></a>
<em>compile-time</em>,
but is postponed until the program is actually executed: only then it is
determined which member function will actually be called.
<p>
<a name="virfunc"></a><a name="l199"></a>
<h2>14.1: Virtual functions</h2>
<a name="polymorphism/function"></a>The default behavior of the activation of a member function via a pointer or
<a name="an1928"></a>
reference is that the type of the pointer (or reference) determines the
function that is called. E.g., a <code>Vehicle *</code> will activate <code>Vehicle</code>'s
member functions, even when pointing to an object of a derived class. This is
referred to as <em>early</em> or
    <a name="an1929"></a>
 <a name="an1930"></a>
<em>static binding</em>, since the type of function is known
<a name="an1931"></a>
compile-time. The <em>late</em> <a name="an1932"></a>
 or <a name="an1933"></a>
<em>dynamic binding</em> is
achieved in <strong>C++</strong> using <em>virtual member functions</em>.
<p>
A member function becomes a <a name="an1934"></a>
virtual member function when its declaration
starts with the keyword <a name="an1935"></a>
<code>virtual</code>. Once a function is declared <code>virtual</code>
in a <a name="an1936"></a>
base class, it remains a virtual member function in all derived
classes; even when the keyword <code>virtual</code> is not repeated in a
    <a name="an1937"></a>
derived class.
<p>
As far as the vehicle classification system is concerned (see section
<a href="cplusplus13.html#VehicleSystem">13.1</a>) the two member functions <code>weight()</code> and
<code>setWeight()</code> might well be declared <code>virtual</code>. The relevant sections of
the class definitions of the class <code>Vehicle</code> and <code>Truck</code> are shown
below. Also, we show the implementations of the member functions
<code>weight()</code> of the two classes:
        <pre>
    class Vehicle
    {
        public:
            virtual int weight() const;
            virtual void setWeight(int wt);
    };

    class Truck: public Vehicle
    {
        public:
            void setWeight(int engine_wt, int trailer_wt);
            int weight() const;
    };

    int Vehicle::weight() const
    {
        return (weight);
    }

    int Truck::weight() const
    {
        return (Auto::weight() + trailer_wt);
    }
</pre>
    Note that the keyword <code>virtual</code> <em>only</em> needs to appear in the
<code>Vehicle</code> base class. There is no need (but there is also no <a name="an1938"></a>
penalty) to
repeat it in derived classes: once <code>virtual</code>, always <code>virtual</code>. On the
other hand, a function may be declared <code>virtual</code> <em>anywhere</em> in a
    <a name="an1939"></a>
class hierarchy: the compiler will be perfectly happy if <code>weight()</code>
is declared <code>virtual</code> in <code>Auto</code>, rather than in <code>Vehicle</code>. The specific
characteristics of virtual member functions would then, for the member
function <code>weight()</code>, only appear with <code>Auto</code> (and its derived classes)
pointers or references. With a <code>Vehicle</code> pointer, <a name="an1940"></a>
static binding would
remain to be used.  The effect of <a name="an1941"></a>
late binding is illustrated below:
        <pre>
    Vehicle v(1200);            // vehicle with weight 1200
    Truck t(6000, 115,          // truck with cabin weight 6000, speed 115,
          "Scania", 15000);     // make Scania, trailer weight 15000
    Vehicle *vp;                // generic vehicle pointer

    int main()
    {
        vp = &amp;v;                            // see (1) below
        cout &lt;&lt; vp-&gt;weight() &lt;&lt; endl;

        vp = &amp;t;                            // see (2) below
        cout &lt;&lt; vp-&gt;weight() &lt;&lt; endl;

        cout &lt;&lt; vp-&gt;speed() &lt;&lt; endl;     // see (3) below
    }
</pre>
    Since the function <code>weight()</code> is defined <code>virtual</code>, <a name="an1942"></a>
late binding
is used:
    <ul>
    <li> at (1), <code>Vehicle::weight()</code> is called.
    <li> at (2) <code>Truck::weight()</code> is called.
    <li> at (3) a syntax error is generated. The member
        <code>speed()</code> is no member of <code>Vehicle</code>, and hence not callable via
a <code>Vehicle*</code>.
    </ul>
    The example illustrates that <a name="an1943"></a>

        <a name="an1944"></a>
 when a pointer to a class is used
<em>only the functions which are members of that class can be called</em>.  These
functions <em>may</em> be <code>virtual</code>. However, this only influences the type of
binding (early vs. late) and not the set of member functions that is visible
to the pointer.
<p>
A virtual member function cannot be a <a name="an1945"></a>
static member function: a virtual
member function is still an ordinary member function in that it has a <a name="an1946"></a>
<code>this</code>
pointer. As static member functions have no <code>this</code> pointer, they cannot be
declared virtual.
<p>
<a name="VIRTDES"></a><a name="l200"></a>
<h2>14.2: Virtual destructors</h2>
<a name="polymorphism/destructor"></a>When the operator <code>delete</code> releases memory occupied by a dynamically
allocated object, or when an object goes <a name="an1947"></a>
out of scope, the appropriate
<a name="an1948"></a>
destructor is called to ensure that memory allocated by the object is also
deleted. Now consider the following code fragment (cf. section
<a href="cplusplus13.html#VehicleSystem">13.1</a>):
        <pre>
    Vehicle *vp = new Land(1000, 120);

    delete vp;          // object destroyed
</pre>
    In this example an object of a derived class (<code>Land</code>) is destroyed using
a base class pointer (<code>Vehicle *</code>). For a `standard' class definition this
will mean that <code>Vehicle</code>'s destructor is called, instead of the <code>Land</code>
object's destructor. This not only results in a <a name="an1949"></a>
memory leak when memory is
allocated in <code>Land</code>, but it will also prevent any other task, normally
performed by the derived class's destructor from being completed (or, better:
started). A Bad Thing.
<p>
In <strong>C++</strong> this problem is solved using <a name="an1950"></a>
 <em>virtual
destructors</em>.  By applying the keyword <code>virtual</code> to the declaration of a
<a name="an1951"></a>
destructor the appropriate derived class destructor is activated when the
argument of the <a name="an1952"></a>
<code>delete</code> operator is a <a name="an1953"></a>
base class pointer. In the
following partial class definition the declaration of such a virtual
destructor is shown:
        <pre>
    class Vehicle
    {
        public:
            virtual ~Vehicle();
            virtual size_t weight() const;
    };
</pre>
    By declaring a virtual destructor, the above <code>delete</code> operation
(<code>delete vp</code>) will correctly call <code>Land</code>'s destructor, rather than
<code>Vehicle</code>'s destructor.
<p>
From this discussion we are now able to formulate the following situations
in which a <a name="an1954"></a>
 destructor should be defined:
    <ul>
    <li> A destructor should be defined when memory is allocated and managed
by objects of the class.
    <li> This destructor should be defined as a <em>virtual</em> destructor if the
class contains at least one virtual member function, to prevent incomplete
destruction of derived class objects when destroying objects using base class
pointers or references pointing to derived class objects (see the initial
paragraphs of this section)
    </ul>
    In the second case, the destructor doesn't have any special tasks to
perform. In these cases the virtual
    <a name="an1955"></a>
 <a name="an1956"></a>

    destructor is given an empty body. For example, the definition of
<code>Vehicle::~Vehicle()</code> may be as simple as:
        <pre>
    Vehicle::~Vehicle()
    {}
</pre>
    Often the destructor will be defined <a name="an1957"></a>
inline below the  
    <a name="an1958"></a>
 <a name="an1959"></a>
class interface.  
<p>
<strong>temporary note</strong>: With the gnu compiler 4.1.2 an annoying bug prevents
        <a name="an1960"></a>

<em>virtual destructors</em> to be defined inline below their class interfaces
without explicitly declaring the virtual destructor as inline within the
interface. Until the bug has been repaired, inline virtual destructors should
be defined as follows (using the class <code>Vehicle</code> as an example):
        <pre>
    class Vehicle
    {
        ...
        public:
            inline virtual ~Vehicle();  // note the `inline'
            ...
    };

    inline Vehicle::~Vehicle()          // inline implementation
    {}                                  // is kept unaltered.
</pre>
<p>
<a name="l201"></a>
<h2>14.3: Pure virtual functions</h2>
<a name="polymorphism/pure"></a>Until now the base class <code>Vehicle</code> contained its own, concrete,
implementations of the virtual functions <code>weight()</code> and <code>setWeight()</code>. In
<strong>C++</strong> it is also possible only to <em>mention</em> virtual member functions in a
<a name="an1961"></a>
base class, without actually defining them. The functions are concretely
implemented in a <a name="an1962"></a>
derived class. This approach, in some languages (like
 <strong>C#, Delphi</strong><a name="an1963"></a>
 and <strong>Java</strong>) known as an <a name="an1964"></a>
<em>interface</em>,
defines a <a name="an1965"></a>
<em>protocol</em>, which <em>must</em> be implemented by derived
classes. This implies that derived classes must take care of the actual
definition: the <strong>C++</strong> compiler will not allow the definition of an object of
a class in which one or more member functions are left undefined.  The base
class thus enforces a protocol by declaring a function by its name, return
value and arguments.  The derived classes must take care of the actual
<a name="an1966"></a>
implementation. The base class itself defines therefore only a <em>model</em> or
<em>mold</em>, to be used when other classes are derived. Such base classes are
also called <a name="an1967"></a>

    <a name="an1968"></a>
<em>abstract classes</em>
    or <em>abstract base classes</em>. Abstract base classes are the foundation of
many <a name="an1969"></a>
<em>design patterns</em> (cf. <em>Gamma et al.</em> (1995)) <a name="an1970"></a>
,
allowing the programmer to create highly <a name="an1971"></a>
<em>reusable software</em>. Some of these
design patterns are covered by the Annotations (e.g, the <a name="an1972"></a>
<em>Template Method</em>
in section <a href="cplusplus20.html#FORK">20.3</a>), but for a thorough discussion of Design Patterns the
reader is referred to Gamma <em>et al.</em>'s book.
<p>
Functions that are only declared in the base class are
called <a name="an1973"></a>
<em>pure virtual functions</em>. A function is made pure virtual by
prefixing  the keyword <a name="an1974"></a>
<code>virtual</code> to its declaration and by postfixing it
with <a name="an1975"></a>
<code>= 0</code>. An example of a pure virtual function occurs in the following
listing, where the definition of a class <code>Object</code> requires the
implementation of the <a name="an1976"></a>
conversion operator <a name="an1977"></a>
<code>operator string()</code>:
        <pre>
    #include &lt;string&gt;

    class Object
    {
        public:
            virtual operator std::string() const = 0;
    };
</pre>
    Now, all classes derived from <code>Object</code> <em>must</em> implement the
<code>operator string()</code> member function, or their objects cannot be
constructed. This is neat: all objects derived from <code>Object</code> can now always
be considered <code>string</code> objects, so they can, e.g., be inserted into
<a name="an1978"></a>
<code>ostream</code> objects.
<p>
Should the <a name="an1979"></a>
virtual destructor of a base class be a pure virtual
function? The answer to this question is no: a class such as <code>Vehicle</code>
should not <em>require</em> derived classes to define a
destructor. In contrast, <code>Object::operator string()</code> <em>can</em> be a pure
virtual function: in this case the base class defines a protocol which must be
adhered to.
<p>
Realize what would happen if we would define the destructor of a base
class as a pure virtual destructor: according to the <a name="an1980"></a>
<em>compiler</em>, the
derived class object can be constructed: as its destructor is defined, the
derived class is not a pure abstract class. However, inside the derived class
destructor, the destructor of its base class is implicitly called. This
destructor was never defined, and the <a name="an1981"></a>
<em>linker</em> will loudly complain about
an <a name="an1982"></a>
undefined reference to, e.g., <code>Virtual::~Virtual()</code>.
<p>
Often, but not necessarily always, pure virtual member functions are
<code>const</code> <a name="an1983"></a>
 member functions. This allows the
construction of constant derived class objects. In other situations this might
not be necessary (or realistic), and <a name="an1984"></a>
non-constant member functions might be
required. The general rule for <code>const</code> member functions applies also to pure
virtual functions: if the member function will alter the object's data
members, it cannot be a <code>const</code> member function. Often abstract base classes
have <a name="an1985"></a>
 <a name="an1986"></a>
no data members. However, the
prototype of the pure virtual member function must be used again in derived
classes. If the implementation of a pure virtual function in a derived class
alters the data of the derived class object, than <em>that</em> function cannot be
declared as a <code>const</code> member function. Therefore, the constructor of an
abstract base class should well consider whether a pure virtual member
function should be a <code>const</code> member function or not.
<p>
<a name="l202"></a>
<h3>14.3.1: Implementing pure virtual functions</h3>
    <a name="polymorphism/implementing"></a>Pure virtual member functions may be implemented. To implement a pure virtual
    <a name="an1987"></a>
member function: pure virtual and implemented
    <a name="an1988"></a>

    <a name="an1989"></a>

 member function, provide it with its normal <code>= 0;</code> specification, but
implement it nonetheless. Since the <code>= 0;</code> ends in a semicolon, the pure
virtual member is always at most a declaration in its class, but an
implementation may either be provided in-line below the class interface or it
may be defined as a non-inline member function in a source file of its own.
<p>
Pure virtual member functions may be called from derived class objects or
from its class or derived class members by specifying the base class and scope
resolution operator with the function to be called. The following small
program shows some examples:
<p>
<pre>
#include &lt;iostream&gt;

class Base
{
    public:
        virtual ~Base();
        virtual void pure() = 0;
};

inline Base::~Base()
{}

inline void Base::pure()
{
    std::cout &lt;&lt; "Base::pure() called\n";
}

class Derived: public Base
{
    public:
        virtual void pure();
};

inline void Derived::pure()
{
    Base::pure();
    std::cout &lt;&lt; "Derived::pure() called\n";
}

int main()
{
    Derived derived;

    derived.pure();
    derived.Base::pure();

    Derived *dp = &amp;derived;

    dp-&gt;pure();
    dp-&gt;Base::pure();
}
// Output:
//      Base::pure() called
//      Derived::pure() called
//      Base::pure() called
//      Base::pure() called
//      Derived::pure() called
//      Base::pure() called
</pre>
<p>
Implementing a pure virtual function has limited use. One could argue that
the pure virtual function's implementation may be used to perform tasks that
can already be performed at the base-class level. However, there is no
guarantee that the base class virtual function will actually be called from
the derived class overridden version of the member function (like
a base class constructor that is automatically called from a derived class
constructor). Since the base class implementation will therefore at most be
called optionally its functionality could as well be implemented in a separate
member, which can then be called without the requirement to mention the base
class explicitly.
  
<p>
<a name="MULTIPLEPOLYMORPH"></a><a name="l203"></a>
<h2>14.4: Virtual functions in multiple inheritance</h2>
<a name="polymorphism/multiple"></a>As mentioned in chapter <a href="cplusplus13.html#INHERITANCE">13</a> a class may be derived from multiple
base classes. Such a derived class inherits the properties of all its base
classes. Of course, the base classes themselves may be derived from classes
yet higher in the hierarchy.
<p>
Consider what would happen if more than one `path' would lead from the
    <a name="an1990"></a>
derived class
    to the <a name="an1991"></a>
base class. This is illustrated in the code example below: a
class <code>Derived</code> is doubly derived from a class <code>Base</code>:
        <pre>
    class Base
    {
        int d_field;
        public:
            void setfield(int val);
            int field() const;
    };
    inline void Base::setfield(int val)
    { 
        d_field = val; 
    }
    inline int field() const
    { 
        return d_field; 
    }

    class Derived: public Base, public Base
    {
    };
</pre>
    Due to the double derivation, the functionality of <code>Base</code> now occurs
twice in <code>Derived</code>. This leads to <a name="an1992"></a>
ambiguity: when the function
<code>setfield()</code> is called for a <code>Derived</code> object, <em>which</em> function should
that be, since there are two? In such a duplicate derivation, C++ compilers
will normally refuse to generate code and will (correctly) identify an error.
<p>
The above code clearly duplicates its base class in the derivation, which can
of course easily be avoided by not doubly deriving from <code>Base</code>. But
duplication of a base class can also occur through <a name="an1993"></a>
nested inheritance,
where an object is derived from, e.g., an <code>Auto</code> and from an <code>Air</code> (see
the vehicle classification system, section <a href="cplusplus13.html#VehicleSystem">13.1</a>). Such a class
would be needed to represent, e.g., a flying car&nbsp;(such as the one in
James Bond vs. the Man with the Golden Gun...). An <code>AirAuto</code> would
ultimately contain two <code>Vehicles</code>, and hence two <code>weight</code> fields, two
<code>setWeight()</code> functions and two <code>weight()</code> functions.
<p>
<a name="l204"></a>
<h3>14.4.1: Ambiguity in multiple inheritance</h3>
    <a name="polymorphism/ambiguity"></a>Let's investigate closer why an <code>AirAuto</code> introduces <a name="an1994"></a>
ambiguity, when
derived from <code>Auto</code> and <code>Air</code>.
    <ul>
    <li> An <code>AirAuto</code> is an <code>Auto</code>, hence a <code>Land</code>, and hence a
<code>Vehicle</code>.
    <li> However, an <code>AirAuto</code> is also an <code>Air</code>, and hence a <code>Vehicle</code>.
    </ul>
    The duplication of <code>Vehicle</code> data is further illustrated in
Figure <a href="cplusplus14.html#ambiguity">13</a>.
    <a name="ambiguity"></a><p><center><img src="polymorphism/ambiguity.gif" align="bottom" alt="Figure 13 is shown here."/><br>
Figure 13: Duplication of a base class in multiple derivation.
</center><p><br>

    The internal organization of an <code>AirAuto</code> is shown in
Figure <a href="cplusplus14.html#InternalOrganization">14</a>
    <a name="InternalOrganization"></a><p><center><img src="polymorphism/internal.gif" align="bottom" alt="Figure 14 is shown here."/><br>
Figure 14: Internal organization of an <code>AirAuto</code> object.
</center><p><br>

    The <strong>C++</strong> compiler will detect the ambiguity in an <code>AirAuto</code> object,
and will therefore fail to compile a statement like:
        <pre>
    AirAuto cool;

    cout &lt;&lt; cool.weight() &lt;&lt; endl;
</pre>
    The question of which member function <code>weight()</code> should be called,
cannot be answered by the compiler. The programmer has two possibilities to
resolve the ambiguity explicitly:
    <ul>
    <li> First, the function call where the ambiguity occurs can be
modified. The ambiguity is resolved using the <a name="an1995"></a>
scope resolution operator:
        <pre>
    // let's hope that the weight is kept in the Auto
    // part of the object..
    cout &lt;&lt; cool.Auto::weight() &lt;&lt; endl;
</pre>
    Note the position of the scope operator and the class name: before the name
of the member function itself.
    <li> Second, a dedicated function <code>weight()</code> could be created for
the class <code>AirAuto</code>:
        <pre>
    int AirAuto::weight() const
    {
        return Auto::weight();
    }
</pre>
    </ul>
    The second possibility from the two above is preferable, since it relieves
the programmer who uses the class <code>AirAuto</code> of special precautions.
<p>
However, apart from these explicit solutions, there is a more elegant one,
discussed in the next section.
<p>
<a name="VIRTUALBASE"></a><a name="l205"></a>
<h3>14.4.2: Virtual base classes</h3>
    <a name="polymorphism/base"></a>    As illustrated in Figure <a href="cplusplus14.html#InternalOrganization">14</a>, an <code>AirAuto</code> represents
<em>two</em> <code>Vehicle</code>s. The result is not only an
<a name="an1996"></a>
ambiguity in the functions which access the <code>weight</code> data, but also the
presence of two <code>weight</code> fields. This is somewhat redundant, since we can
assume that an <code>AirAuto</code> has just one weight.
<p>
We can achieve the situation that an <code>AirAuto</code> is only one <code>Vehicle</code>,
yet used multiple derivation.  This is realized by defining the <a name="an1997"></a>
base class
that is multiply mentioned in a <a name="an1998"></a>
derived class' inheritance tree as a
    <a name="an1999"></a>
<em>virtual base class</em>.
For the class <code>AirAuto</code> this means that the derivation of <code>Land</code> and
<code>Air</code> is changed:
        <pre>
    class Land: virtual public Vehicle
    {
        // etc
    };

    class Auto: public Land
    {
        // etc
    };


    class Air: virtual public Vehicle
    {
        // etc
    };

    class AirAuto: public Auto, public Air
    {
    };
</pre>
    The <a name="an2000"></a>
virtual derivation ensures that via the <code>Land</code> route, a
<code>Vehicle</code> is only added to a class when a virtual base class was not yet
present. The same holds true for the <code>Air</code> route. This means that we can no
longer say via which route a <code>Vehicle</code> becomes a part of an <code>AirAuto</code>; we
can only say that there is an embedded <code>Vehicle</code> object.  The internal
organization of an <code>AirAuto</code> after virtual derivation is shown in
Figure <a href="cplusplus14.html#VirtualBaseClass">15</a>.
    <a name="VirtualBaseClass"></a><p><center><img src="polymorphism/virtbase.gif" align="bottom" alt="Figure 15 is shown here."/><br>
Figure 15: Internal organization of an <code>AirAuto</code> object when the base
            classes are virtual.
</center><p><br>

    Note the following:
    <ul>
    <li> When base classes of a class using multiple derivation are themselves
virtually derived from a base class (as shown above), the
    <a name="an2001"></a>
base class constructor normally called when the derived class
constructor is called, is no longer used: its
    <a name="an2002"></a>
 base class initializer is
<em>ignored</em>. Instead, the base class constructor will be called independently
from the derived class constructors. Assume we have two classes, <code>Derived1</code>
and <code>Derived2</code>, both (possibly virtually) derived from <code>Base</code>. We will
address the <a name="an2003"></a>
 question which
constructors will be called when a class <code>Final: public Derived1, public
Derived2</code> is defined. To distinguish the several constructors that are
involved, we will use <code>Base1()</code> to indicate the <code>Base</code> class constructor
that is called as base class initializer for <code>Derived1</code> (and analogously:
<code>Base2()</code> belonging to <code>Derived2</code>), while <code>Base()</code> indicates the default
constructor of the class <code>Base</code>. Apart from the <code>Base</code> class constructor,
we use <code>Derived1()</code> and <code>Derived2()</code> to indicate the base class
initializers for the class <code>Final</code>. We now distinguish the following
cases when constructing the class <code>Final: public Derived1, public
Derived2</code>:
        <ul>
        <li> classes:
                <pre>
                    Derived1: public Base
                    Derived2: public Base
</pre>
            <blockquote>This is the normal, non virtual multiple derivation. There
                are two <code>Base</code> classes in the <code>Final</code> object, and the
                following constructors will be called (in the mentioned
                order):
                <pre>
                    Base1(),
                    Derived1(),
                    Base2(),
                    Derived2()
</pre>
            </blockquote>
        <li> classes:
                <pre>
                    Derived1: public Base
                    Derived2: virtual public Base
</pre>
            <blockquote>Only <code>Derived2</code> uses virtual derivation. For the
                <code>Derived2</code> part the base class initializer will be omitted,
                and the default <code>Base</code> class constructor will be
                called. Furthermore, this `detached' base class constructor
                will be called <em>first</em>:
                <pre>
                    Base(),
                    Base1(),
                    Derived1(),
                    Derived2()
</pre>
                Note that <code>Base()</code> is called first, <em>not</em>
                <code>Base1()</code>. Also note that, as only one derived class uses
                virtual derivation, there are still <em>two</em> <code>Base</code> class
                objects in the eventual <code>Final</code> class. Merging of
                <a name="an2004"></a>
 base classes only occurs with
                <a name="an2005"></a>
multiple virtual base classes.
            </blockquote>
        <li> classes:
                <pre>
                    Derived1: virtual public Base
                    Derived2: public Base
</pre>
            <blockquote>Only <code>Derived1</code> uses virtual derivation. For the
                <code>Derived1</code> part the base class initializer will now be
                omitted, and the default <code>Base</code> class constructor will be
                called instead. Note the difference with the first case:
                <code>Base1()</code> is replaced by <code>Base()</code>. Should <code>Derived1</code>
                happen to use the default <code>Base</code> constructor, no difference
                would be noted here with the first case:
                <pre>
                    Base(),
                    Derived1(),
                    Base2(),
                    Derived2()
</pre>
            </blockquote>
        <li> classes:
                <pre>
                    Derived1: virtual public Base
                    Derived2: virtual public Base
</pre>
            <blockquote>Here both derived classes use virtual derivation, and so
                only <em>one</em> <code>Base</code> class object will be present in the
                <code>Final</code> class. Note that now only one <code>Base</code> class
                constructor is called: for the detached (merged) <code>Base</code>
                class object:
                <pre>
                    Base(),
                    Derived1(),
                    Derived2()
</pre>
            </blockquote>
        </ul>
    <li> Virtual derivation is, in contrast to virtual functions, a pure
<a name="an2006"></a>
compile-time issue: whether a derivation is virtual or not defines
how the compiler builds a class definition from other classes.
    </ul>
    Summarizing, using virtual derivation avoids ambiguity when member
functions of a base class are called. Furthermore,
    <a name="an2007"></a>
duplication of data members is avoided.
<p>
<a name="l206"></a>
<h3>14.4.3: When virtual derivation is not appropriate</h3>
    <a name="polymorphism/notvirtual"></a>In contrast to the previous definition of a class such as <code>AirAuto</code>,
situations may arise where the <a name="an2008"></a>
 double
presence of the members of a base class is appropriate. To illustrate this,
consider the definition of a <code>Truck</code> from section <a href="cplusplus13.html#Truck">13.4</a>:
        <pre>
    class Truck: public Auto
    {
        int d_trailer_weight;

        public:
            Truck();
            Truck(int engine_wt, int sp, char const *nm,
                   int trailer_wt);

            void setWeight(int engine_wt, int trailer_wt);
            int weight() const;
    };

    Truck::Truck(int engine_wt, int sp, char const *nm,
                  int trailer_wt)
    :
        Auto(engine_wt, sp, nm)
    {
        d_trailer_weight = trailer_wt;
    }

    int Truck::weight() const
    {
        return                  // sum of:
            Auto::weight() +    //   engine part plus
            trailer_wt;         //   the trailer
    }
</pre>
    This definition shows how a <code>Truck</code> object is constructed to contain two
weight fields: one via its derivation from <code>Auto</code> and one via its own <code>int
d_trailer_weight</code> data member. Such a definition is of course valid, but it
could also be rewritten. We could derive a <code>Truck</code> from an <code>Auto</code>
<em>and</em> from a <code>Vehicle</code>, thereby explicitly requesting the double presence
of a <code>Vehicle</code>; one for the weight of the engine and cabin, and one for the
weight of the trailer.
A small point of interest here is that a derivation like
        <pre>
    class Truck: public Auto, public Vehicle
</pre>
    is not accepted by the <strong>C++</strong> compiler: a <code>Vehicle</code> is already part of
an <code>Auto</code>, and is therefore not needed. An <a name="an2009"></a>
intermediate class solves
the problem: we derive a class <code>TrailerVeh</code> from <code>Vehicle</code>, and <code>Truck</code>
from <code>Auto</code> and from <code>TrailerVeh</code>.  All ambiguities concerning the member
functions are then be solved for the class <code>Truck</code>:
        <pre>
    class TrailerVeh: public Vehicle
    {
        public:
            TrailerVeh(int wt);
    };

	inline TrailerVeh::TrailerVeh(int wt)
	:
	    Vehicle(wt)
	{}
	
    class Truck: public Auto, public TrailerVeh
    {
        public:
            Truck();
            Truck(int engine_wt, int sp, char const *nm, int trailer_wt);
            void setWeight(int engine_wt, int trailer_wt);
            int weight() const;
    };

	inline Truck::Truck(int engine_wt, int sp, char const *nm,
	                    int trailer_wt)
	:
	    Auto(engine_wt, sp, nm),
	    TrailerVeh(trailer_wt)
	{}
	
    inline int Truck::weight() const
    {
        return                      // sum of:
            Auto::weight() +        //   engine part plus
            TrailerVeh::weight();   //   the trailer
    }
</pre>
<p>
<a name="RTTI"></a><a name="l207"></a>
<h2>14.5: Run-time type identification</h2>
<a name="polymorphism/rtti"></a><strong>C++</strong> offers two ways to <a name="an2010"></a>
retrieve the type of objects and expressions
while the program is running. The possibilities of <strong>C++</strong>'s
    <a name="an2011"></a>
<em>run-time type identification</em> are limited compared to
languages like <a name="an2012"></a>
 <strong>Java</strong>. Normally, <strong>C++</strong> uses
    <a name="an2013"></a>
static type checking and <a name="an2014"></a>
static type identification. Static type
checking and determination is possibly safer and certainly more efficient than
run-time type identification, and should therefore be used wherever
possible. Nonetheles, <strong>C++</strong> offers run-time type identification by providing
the <a name="an2015"></a>
<em>dynamic cast</em> and <a name="an2016"></a>
<code>typeid</code> operators.
    <ul>
    <li> The <a name="an2017"></a>
<code>dynamic_cast&lt;&gt;()</code> operator can be used to convert a base
class <a name="an2018"></a>
 pointer or reference to a
derived class pointer or reference. This is called <a name="an2019"></a>
<em>down-casting</em>.
        <li> The <a name="an2020"></a>
<code>typeid</code> operator returns the actual type of an expression.
            <a name="an2021"></a>

    </ul>
    These operators operate on class type objects, containing at least one
        <a name="an2022"></a>
virtual member function.
<p>
<a name="DYNAMICCAST"></a><a name="l208"></a>
<h3>14.5.1: The dynamic_cast operator</h3>
        <a name="polymorphism/dynamiccast"></a>The <a name="an2023"></a>
<code>dynamic_cast&lt;&gt;()</code> operator is used to convert a <a name="an2024"></a>
base class pointer
or <a name="an2025"></a>
 reference to, respectively, a
<a name="an2026"></a>
derived class pointer or reference.
<p>
A dynamic cast is performed <a name="an2027"></a>
run-time. A prerequisite for using the
dynamic cast <a name="an2028"></a>
 operator is the existence of at
least one virtual member function in the base class.
<p>
In the following example a pointer to the class <code>Derived</code> is obtained from
the <code>Base</code> class pointer <code>bp</code>:
        <pre>
    class Base
    {
        public:
            virtual ~Base();
    };

    class Derived: public Base
    {
        public:
            char const *toString();
    };
	inline char const *Derived::toString()
	{
	    return "Derived object";
	}
	
    int main()
    {
        Base *bp;
        Derived *dp,
        Derived d;

        bp = &amp;d;

        dp = dynamic_cast&lt;Derived *&gt;(bp);

        if (dp)
            cout &lt;&lt; dp-&gt;toString() &lt;&lt; endl;
        else
            cout &lt;&lt; "dynamic cast conversion failed\n";
    }
</pre>
    Note the test: in the <code>if</code> condition the success of the dynamic cast is
checked. This must be done <em>run-time</em>, as the compiler can't do this all by
itself. If a base class pointer is provided, the dynamic cast operator returns
0 on failure and a pointer to the requested derived class on
success. Consequently, if there are multiple derived classes, a series of
checks could be performed to find the actual derived class to which the
pointer points (In the next example derived classes are only declared):
        <pre>
    class Base
    {
        public:
            virtual ~Base();
    };
    class Derived1: public Base;
    class Derived2: public Base;

    int main()
    {
        Base *bp;
        Derived1 *d1,
        Derived1 d;
        Derived2 *d2;

        bp = &amp;d;

        if ((d1 = dynamic_cast&lt;Derived1 *&gt;(bp)))
            cout &lt;&lt; *d1 &lt;&lt; endl;
        else if ((d2 = dynamic_cast&lt;Derived2 *&gt;(bp)))
            cout &lt;&lt; *d2 &lt;&lt; endl;
    }
</pre>
    Alternatively, a reference to a base class object may be available. In
this case the <code>dynamic_cast&lt;&gt;()</code> operator will throw an <a name="an2029"></a>
exception if it
fails. For example:
        <pre>
    #include &lt;iostream&gt;

    class Base
    {
        public:
            virtual ~Base();
            virtual char const *toString();
    };
    inline Base::~Base()
    {}
    inline char const *Base::toString()
    {
        return "Base::toString() called";
    }

    class Derived1: public Base
    {};

    class Derived2: public Base
    {};

    void process(Base &amp;b)
    {
        try
        {
            std::cout &lt;&lt; dynamic_cast&lt;Derived1 &amp;&gt;(b).toString() &lt;&lt; std::endl;
        }
        catch (std::bad_cast)
        {}

        try
        {
            std::cout &lt;&lt; dynamic_cast&lt;Derived2 &amp;&gt;(b).toString() &lt;&lt; std::endl;
        }
        catch (std::bad_cast)
        {
            std::cout &lt;&lt; "Bad cast to Derived2\n";
        }
    }

    int main()
    {
        Derived1 d;

        process(d);
    }
    /*
        Generated output:

        Base::toString() called
        Bad cast to Derived2
    */
</pre>
    In this example the value <a name="an2030"></a>
<code>std::bad_cast</code> <a name="an2031"></a>
 is
introduced. The <code>std::bad_cast</code> exception is thrown if the
dynamic cast of a reference to a derived class object fails.
<p>
Note the form of the <code>catch</code> clause: <code>bad_cast</code> is the name of a
        <a name="an2032"></a>

    type. In section <a href="cplusplus16.html#EMPTYENUM">16.4.1</a> the construction of such a type is
discussed.
<p>
The dynamic cast operator is a useful tool when an existing base class cannot
or should not be modified (e.g., when the sources are not available), and a
derived class may be modified instead. Code receiving a base class pointer or
reference may then perform a dynamic cast to the derived class to access the
derived class's functionality.
<p>
Casts from a base class reference or pointer to a derived class reference or
pointer are called <a name="an2033"></a>
<em>downcasts</em>.
<p>
One may wonder what the difference is between a <code>dynamic_cast</code> and a
<code>reinterpret_cast</code>. Of course, the <code>dynamic_cast</code> may be used with
references and the <code>reinterpret_cast</code> can only be used for pointers. But
what's the difference when both arguments are pointers?
<p>
When the <code>reinterpret_cast</code> is used, we tell the compiler that it literally
should re-interpret a block of memory as something else. A well known example
is obtaining the individual bytes of an <code>int</code>. An <code>int</code> consists of
<code>sizeof(int)</code> bytes, and these bytes can be accessed by reinterpreting the
location of the <code>int</code> value as a <code>char *</code>. When using a
<code>reinterpret_cast</code> the compiler offers absolutely no safeguard. The compiler
will happily <code>reinterpret_cast</code> an <code>int *</code> to a <code>double *</code>, but the
resulting dereference produces at the very least a meaningless value.
<p>
The <code>dynamic_cast</code> will also reinterpret a block of memory as something
else, but here a run-time safeguard is offered. The dynamic cast fails when
the requested type doesn't match the actual type of the object we're pointing
at. The <code>dynamic_cast</code>'s purpose is also much more restricted than the
<code>reinterpret_cast</code>'s purpose, as it should only be used for downcasting to
derived classes having virtual members.
<p>
<a name="TYPEID"></a><a name="l209"></a>
<h3>14.5.2: The `typeid' operator</h3>
        <a name="polymorphism/typeid"></a>As with the <a name="an2034"></a>
<code>dynamic_cast&lt;&gt;()</code> operator, the <a name="an2035"></a>
<code>typeid</code> is usually applied
to base class objects, that are actually derived class objects. Similarly, the
base class should contain one or more virtual functions.
<p>
In order to use the <code>typeid</code> operator, source files must
    <a name="an2036"></a>

        <pre>
    #include &lt;typeinfo&gt;
</pre>
    Actually, the <code>typeid</code> operator returns an object of type <a name="an2037"></a>
<code>type_info</code>,
which may, e.g., be compared to other <code>type_info</code> objects.
<p>
The class <code>type_info</code> may be implemented differently by different
implementations, but at the very least it has the following interface:
        <pre>
    class type_info
    {
        public:
            virtual ~type_info();
            int operator==(const type_info &amp;other) const;
            int operator!=(const type_info &amp;other) const;
            char const *name() const;
        private:
            type_info(type_info const &amp;other);
            type_info &amp;operator=(type_info const &amp;other);
    };
</pre>
    Note that this class has a <a name="an2038"></a>
private copy constructor and overloaded
<a name="an2039"></a>
 <a name="an2040"></a>

    <a name="an2041"></a>
 assignment operator. This prevents the
normal construction or assignment of a <code>type_info</code> object. Such <code>type_info</code>
objects are constructed and returned by the <code>typeid</code>
operator. Implementations, however, may choose to extend or elaborate the
<code>type_info</code> class and provide, e.g., lists of functions that can be called
with a certain class.
<p>
If the <code>type_id</code> operator is given a base class reference (where the
base class contains at least one virtual function), it will indicate that the
type of its operand is the derived class. For example:
        <pre>
    class Base;     // contains at least one virtual function
    class Derived: public Base;

    Derived d;
    Base    &amp;br = d;

    cout &lt;&lt; typeid(br).name() &lt;&lt; endl;
</pre>
    In this example the <code>typeid</code> operator is given a base class reference.
It will print the text ``<code>Derived</code>'', being the <a name="an2042"></a>
class name of the class
<code>br</code> actually refers to. If <code>Base</code> does not contain virtual functions, the
text ``<code>Base</code>'' would have been printed.
<p>
The <code>typeid</code> operator can be used to determine the name of the actual
type of <a name="an2043"></a>
 expressions, not just of class type
objects. For example:
        <pre>
    cout &lt;&lt; typeid(12).name() &lt;&lt; endl;     // prints:  int
    cout &lt;&lt; typeid(12.23).name() &lt;&lt; endl;  // prints:  double
</pre>
    Note, however, that the above example is suggestive at most of the type
that is printed. It <em>may</em> be <code>int</code> and <code>double</code>, but this is not
necessarily the case. If portability is required, make sure no tests against
these static, built-in text-strings are required. Check out what your compiler
produces in case of doubt.
<p>
In situations where the <code>typeid</code> operator is applied to determine the
type of a derived class, it is important to realize that a base class
<em>reference</em> <a name="an2044"></a>
 should be used as the argument of the
<code>typeid</code> operator. Consider the following example:
        <pre>
    class Base;     // contains at least one virtual function
    class Derived: public Base;

    Base *bp = new Derived;     // base class pointer to derived object

    if (typeid(bp) == typeid(Derived *))    // 1: false
        ...
    if (typeid(bp) == typeid(Base *))       // 2: true
        ...
    if (typeid(bp) == typeid(Derived))      // 3: false
        ...
    if (typeid(bp) == typeid(Base))         // 4: false
        ...
    if (typeid(*bp) == typeid(Derived))     // 5: true
        ...
    if (typeid(*bp) == typeid(Base))        // 6: false
        ...

    Base &amp;br = *bp;

    if (typeid(br) == typeid(Derived))      // 7: true
        ...
    if (typeid(br) == typeid(Base))         // 8: false
        ...
</pre>
    Here, <code>(1)</code> returns <code>false</code> as a <code>Base *</code> is not a <code>Derived
*</code>. <code>(2)</code> returns <code>true</code>, as the two pointer types are the same, <code>(3)</code>
and <code>(4)</code> return <code>false</code> as pointers to objects are not the objects
themselves.
<p>
On the other hand, if <code>*bp</code> is used in the above expressions, then
<code>(1)</code> and <code>(2)</code> return <code>false</code> as an object (or reference to an object)
is not a pointer to an object, whereas <code>(5)</code> now returns <code>true</code>: <code>*bp</code>
actually refers to a <code>Derived</code> class object, and <code>typeid(*bp)</code> will return
<code>typeid(Derived)</code>.  A similar result is obtained if a base class reference
is used: <code>7</code> returning <code>true</code> and <code>8</code> returning <code>false</code>.
<p>
When a <code>0</code>-pointer is passed to the <code>operator typeid</code> a <a name="an2045"></a>
<code>bad_typeid</code>
exception is thrown.
<p>
<a name="POLYSTREAMBUF"></a><a name="l210"></a>
<h2>14.6: Deriving classes from `streambuf'</h2>
<a name="polymorphism/streambuf"></a>The <code>class</code> <a name="an2046"></a>
<code>streambuf</code> (see section <a href="cplusplus05.html#STREAMBUF">5.7</a> and figure
<a href="cplusplus05.html#SBBUFFERS">4</a>) has many (protected) <a name="an2047"></a>
virtual member functions (see section
<a href="cplusplus05.html#SBPROTECTED">5.7.1</a>) that are used by the <a name="an2048"></a>
<code>stream</code> classes using <code>streambuf</code>
objects. By deriving a class from the <code>class streambuf</code> these member
functions may be overriden in the derived classes, thus implementing a
specialization of the class <code>streambuf</code> for which the standard <a name="an2049"></a>
<code>istream</code>
and <a name="an2050"></a>
<code>ostream</code> objects can be used.
<p>
Basically, a <code>streambuf</code> interfaces to some <a name="an2051"></a>
<em>device</em>. The normal behavior
of the <code>stream</code>-class objects remains unaltered. So, a <a name="an2052"></a>
<code>string</code> extraction
from a <code>streambuf</code> object will still return a consecutive sequence of non
white space delimited characters. If the derived class is used for
    <a name="an2053"></a>
<em>input operations</em>, the following member functions are serious
candidates to be overridden. Examples in which some of these functions are
overridden will be given later in this section:
    <ul>
    <li><a name="an2054"></a>
<code>int streambuf::pbackfail(int c)</code>:<blockquote>This member is called when
            <ul>
            <li><code>gptr() == 0</code>: no buffering used,
            <li><code>gptr() == eback()</code>: no more room to push back,
            <li><code>*gptr() != c</code>: a different character than the next character
                to be read must be pushed back.
            </ul>
        If <code>c == endOfFile()</code> then the input device must be reset one
        character,  otherwise <code>c</code> must be prepended to the characters to be
        read. The function will return <code>EOF</code> on failure. Otherwise 0 can
        be
        returned. The function is called when other attempts to push back a
        character fail.
        </blockquote>
    <li><a name="an2055"></a>
<code>streamsize streambuf::showmanyc()</code>:<blockquote>This member must return a guaranteed lower bound on the
        number of characters that can be read from the device before
        <code>uflow()</code> or <code>underflow()</code> returns <code>EOF</code>. By default 0 is
        returned (meaning at least 0 characters will be returned before the
        latter two functions will return <code>EOF</code>). When a positive value is
        returned then the next call to the <code>u(nder)flow()</code> member will not
        return <code>EOF</code>.
        </blockquote>
    <li><a name="an2056"></a>
<code>int streambuf::uflow()</code>:<blockquote>By default, this function calls <code>underflow()</code>. If <code>underflow()</code>
        fails, <code>EOF</code> is returned. Otherwise, the next character
        available character is returned as <code>*gptr()</code> following a
        <code>gbump(-1)</code>. The member also moves the pending character that is
        returned
        to the backup sequence. This is different from <code>underflow()</code>,
        which also returns the next available character, but does not alter
        the input position.
        </blockquote>
    <li><a name="an2057"></a>
<code>int streambuf::underflow()</code>:<blockquote>This member is called when
            <ul>
            <li> there is no input buffer (<code>eback() == 0</code>)
            <li><code>gptr() &gt;= egptr()</code>: there are no more pending input
                characters.
            </ul>
        It returns the next available input character, which is the character
        at <code>gptr()</code>, or the first available character from the input device.
<p>
Since this member is eventually used by other member
        functions for reading characters from a device,
        at the very least this member function must be overridden for new
        classes derived from <code>streambuf</code>.
        </blockquote>
    <li><a name="an2058"></a>
<code>streamsize streambuf::xsgetn(char *buffer, streamsize n)</code>:<blockquote>This member function should act as if the returnvalues of <code>n</code>
        calls of <a name="an2059"></a>
<code>snext()</code> are assigned to consecutive locations of
        <code>buffer</code>. If <code>EOF</code> is returned then reading stops. The actual
        number of characters read is returned. Overridden versions could
        optimize the reading process by, e.g., directly accessing the input
        buffer.
        </blockquote>
    </ul>
    When the derived class is used for <a name="an2060"></a>
<em>output operations</em>, the next member
functions should be considered:
    <ul>
    <li><a name="an2061"></a>
<code>int streambuf::overflow(int c)</code>:<blockquote>This member is called to write characters from the pending sequence to
        the output device. Unless <code>c</code> is <code>EOF</code>, when calling this
        function and it returns <code>c</code> it may be assumed that the character
        <code>c</code> is appended to the pending sequence. So, if the pending sequence
        consists of the characters <code>'h', 'e', 'l'</code> and <code>'l'</code>, and <code>c ==
        'o'</code>, then eventually `<code>hello</code>' will be written to the output
        device.
<p>
Since this  member is eventually used by other member
        functions for writing characters to a device,
        at the very least this member function must be overridden for new
        classes derived from <code>streambuf</code>.
<p>
</blockquote>
    <li><a name="an2062"></a>
<code>streamsize streambuf::xsputn(char const *buffer, streamsize n)</code>:<blockquote>This member function should act as if <code>n</code> consecutive locations of
        <code>buffer</code> are passed to  <a name="an2063"></a>
<code>sputc()</code>. If <code>EOF</code> is returned
        by this latter member, then writing stops. The actual
        number of characters written is returned. Overridden versions could
        optimize the writing process by, e.g., directly accessing the output
        buffer.
        </blockquote>
    </ul>
    For derived classes using buffers and supporting seek operations, consider
these member functions:
    <ul>
    <li><a name="an2064"></a>
<code>streambuf *streambuf::setbuf(char *buffer, streamsize n)</code>:<blockquote>This member function is called by the <code>pubsetbuf()</code> member
        function.
        </blockquote>
    <li><a name="an2065"></a>
<code>pos_type streambuf::seekoff(off_type offset, ios::seekdir way,
            ios::openmode mode = ios::in | ios::out)</code>:<blockquote>This member function is called to reset the position of the next
        character to be processed. It is called by <a name="an2066"></a>
<code>pubseekoff()</code>. The
        new position or an invalid position (e.g., -1) is returned.
        </blockquote>
    <li><a name="an2067"></a>
<code>pos_type streambuf::seekpos(pos_type offset,
            ios::openmode mode = ios::in | ios::out)</code>:<blockquote>This member function acts similarly as <code>seekoff()</code>, but operates
        with absolute rather than relative positions.
        </blockquote>
    <li><a name="an2068"></a>
<code>int sync()</code>:<blockquote>This member function flushes all pending characters to the device,
        and/or resets an input device to the position of the first pending
        character, waiting in the input buffer to be consumed. It returns
        0 on success, -1 on failure. As the default <code>streambuf</code> is not
        buffered, the default implementation also returns 0.
        </blockquote>
    </ul>
    Next, consider the following problem, which will be solved by constructing
a class <a name="an2069"></a>
<code>CapsBuf</code> derived from <code>streambuf</code>. The problem is to construct a
streambuf writing its information to the standard output stream in such a way
that all white-space delimited series of characters are capitalized. The class
<code>CapsBuf</code> obviously needs an overridden <code>overflow()</code> member and a minimal
awareness of its state. Its state changes from `Capitalize' to `Literal' as
follows:
    <ul>
    <li> The start state is `Capitalize';
    <li> Change to `Capitalize' after processing a white-space character;
    <li> Change to `Literal' after processing a non-whitespace character.
    </ul>
    A simple variable to remember the last character allows us to keep track
of the current state. Since `Capitalize' is similar to `last character
processed is a white space character' we can simply initialize the variable
with a white space character, e.g., the blank space. Here is the initial
definition of the  class <code>CapsBuf</code>:
        <pre>
#include &lt;iostream&gt;
#include &lt;streambuf&gt;
#include &lt;ctype.h&gt;

class CapsBuf: public std::streambuf
{
    int d_last;

    public:
        CapsBuf()
        :
            d_last(' ')
        {}

    protected:
        int overflow(int c)             // interface to the device.
        {
            std::cout.put(isspace(d_last) ? toupper(c) : c);
            return d_last = c;
        }
};
</pre>
    An example of a program using <code>CapsBuf</code> is:
        <pre>
    #include "capsbuf1.h"
    using namespace std;

    int main()
    {
        CapsBuf     cb;

        ostream     out(&amp;cb);

        out &lt;&lt; hex &lt;&lt; "hello " &lt;&lt; 32 &lt;&lt; " worlds" &lt;&lt; endl;

        return 0;
    }
    /*
        Generated output:

        Hello 20 Worlds
    */
</pre>
    Note the use of the insertion operator, and note that all type and
<a name="an2070"></a>
radix conversions (inserting <a name="an2071"></a>
<code>hex</code> and the value 32, coming out as the
ASCII-characters <code>'2'</code> and <code>'0'</code>) is neatly done by the <a name="an2072"></a>
<code>ostream</code>
object. The real purpose in life for <code>CapsBuf</code> is to capitalize series of
ASCII-characters, and that's what it does very well.
<p>
Next, we realize that inserting characters into streams can also be
realized by a construction like
        <pre>
    cout &lt;&lt; cin.rdbuf();
</pre>
    or, boiling down to the same thing:
        <pre>
    cin &gt;&gt; cout.rdbuf();
</pre>
    Realizing that this is all about streams, we now try, in the <code>main()</code>
function above:
        <pre>
    cin &gt;&gt; out.rdbuf();
</pre>
    We compile and link the program to the executable <code>caps</code>, and start:
        <pre>
    echo hello world | caps
</pre>
    Unfortunately, nothing happens.... Nor do we get any reaction when we try
the statement <code>cin</code> >> <code>cout.rdbuf()</code>. What's wrong here?
<p>
The difference between <code>cout</code> << <code>cin.rdbuf()</code>, which <em>does</em>
produce the expected results and our using of <code>cin</code> >> <code>out.rdbuf()</code>
is that the <code>operator</code>>><code>(streambuf *)</code> (and its insertion
counterpart) member function performs a <code>streambuf</code>-to-<code>streambuf</code> copy
only if the respective
    <a name="an2073"></a>
 stream modes are set up correctly. So, the argument of the
extraction operator must point to a <code>streambuf</code> into which information can
be written. By default, no stream mode is set for a plain <code>streambuf</code>
object. As there is no constructor for a <code>streambuf</code> accepting an
<a name="an2074"></a>
<code>ios::openmode</code>, we force the required <code>ios::out</code> mode by defining an
output buffer using <code>setp()</code>. We do this by defining a buffer, but don't
want to use it, so we let its size be 0. Note that this is something different
than using 0-argument values with <code>setp()</code>, as this would indicate `no
buffering', which would not alter the default situation. Although any non-0
value could be used for the empty <code>[begin, begin)</code> range, we decided to
define a (dummy) local <code>char</code> variable in the constructor, and use
    <a name="an2075"></a>
<code>[&amp;dummy, &amp;dummy)</code> to define the empty buffer. This effectively
defines <code>CapsBuf</code> as an output buffer, thus activating the
        <pre>
    istream::operator&gt;&gt;(streambuf *)
</pre>
    member. As the variable <code>dummy</code> is not used by <code>setp()</code> it may be
defined as a local variable. It's only purpose in life it to indicate to
<code>setp()</code> that no buffer is used. Here is the revised constructor of the
class <code>CapsBuf</code>:
        <pre>
    CapsBuf::CapsBuf()
    :
        d_last(' ')
    {
        char dummy;
        setp(&amp;dummy, &amp;dummy);
    }
</pre>
    Now the program can use either
        <pre>
    out &lt;&lt; cin.rdbuf();
</pre>
    or:
        <pre>
    cin &gt;&gt; out.rdbuf();
</pre>
    Actually, the <code>ostream</code> <a name="an2076"></a>
wrapper isn't really needed here:
        <pre>
    cin &gt;&gt; &amp;cb;
</pre>
    would have produced the same results.
<p>
It is not clear whether the <code>setp()</code> solution proposed here is actually
a <a name="an2077"></a>
<em>kludge</em>. After all, shouldn't the <code>ostream</code> wrapper around <code>cb</code>
inform the <code>CapsBuf</code> that it should act as a <code>streambuf</code> for doing output
operations?
<p>
<a name="POLYMORPHEXCEPTION"></a><a name="l211"></a>
<h2>14.7: A polymorphic exception class</h2>
<a name="polymorphism/exception"></a>Earlier in the Annotations (section <a href="cplusplus08.html#EMPTYTHROW">8.3.1</a>) we hinted at the
possibility of designing a class <code>Exception</code> whose <code>process()</code> member
would behave differently, depending on the kind of exception that was
thrown. Now that we've introduced <a name="an2078"></a>
polymorphism, we can further develop this
example.
<p>
By now it will probably be clear that our class <code>Exception</code> should be a
virtual base class, from which special exception handling classes can be
derived. It could even be argued that <code>Exception</code> can be an
    <a name="an2079"></a>
abstract base class declaring only <a name="an2080"></a>
pure virtual member functions. In
the discussion in section <a href="cplusplus08.html#EMPTYTHROW">8.3.1</a> a member function <code>severity()</code> was
mentioned which might not be a proper candidate for a purely abstract member
function, but for that member we can now use the completely general
    <a name="an2081"></a>
<code>dynamic_cast&lt;&gt;()</code> operator.
<p>
The (abstract) base class <code>Exception</code> is designed as follows:
        <pre>
    #ifndef _EXCEPTION_H_
    #define _EXCEPTION_H_

    #include &lt;iostream&gt;
    #include &lt;string&gt;

    class Exception
    {
        friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;str,
                                        Exception const &amp;e);
        std::string d_reason;

        public:
            virtual ~Exception();
            virtual void process() const = 0;
            virtual operator std::string() const;
        protected:
            Exception(char const *reason);
    };

        inline Exception::~Exception()
        {}
        inline Exception::operator std::string() const
        {
            return d_reason;
        }
        inline Exception::Exception(char const *reason)
        :
            d_reason(reason)
        {}
        inline std::ostream &amp;operator&lt;&lt;(std::ostream &amp;str, Exception const &amp;e)
        {
            return str &lt;&lt; e.operator std::string();
        }

    #endif
</pre>
    The <code>operator string()</code> member function of course replaces the
<code>toString()</code> member used in section <a href="cplusplus08.html#EMPTYTHROW">8.3.1</a>. The <code>friend</code>
<code>operator</code><<<code>()</code> function is using the (virtual) <code>operator string()</code> member so
that we're able to insert an <code>Exception</code> object into an <code>ostream</code>. Apart
from that, notice the use of a <a name="an2082"></a>
virtual destructor, doing nothing.
<p>
A derived class <code>FatalException: public Exception</code> could now be defined
as follows (using a very basic <code>process()</code> implementation indeed):
        <pre>
    #ifndef _FATALEXCEPTION_H_
    #define _FATALEXCEPTION_H_

    #include "exception.h"

    class FatalException: public Exception
    {
        public:
            FatalException(char const *reason);
            void process() const;
    };
        inline FatalException::FatalException(char const *reason)
        :
            Exception(reason)
        {}
        inline void FatalException::process() const
        {
            exit(1);
        }
    #endif
</pre>
<p>
The translation of the example at the end of section <a href="cplusplus08.html#EMPTYTHROW">8.3.1</a> to
the current situation can now easily be made (using derived classes
<code>WarningException</code> and <code>MessageException</code>), constructed like <code>FatalException</code>:
        <pre>
    #include &lt;iostream&gt;
    #include "message.h"
    #include "warning.h"
    using namespace std;

    void initialExceptionHandler(Exception const *e)
    {
        cout &lt;&lt; *e &lt;&lt; endl;         // show the plain-text information

        if
        (
            !dynamic_cast&lt;MessageException const *&gt;(e)
            &amp;&amp;
            !dynamic_cast&lt;WarningException const *&gt;(e)
        )
            throw;                  // Pass on other types of Exceptions

        e-&gt;process();               // Process a message or a warning
        delete e;
    }
</pre>
<p>
<a name="howpolymorfism"></a><a name="l212"></a>
<h2>14.8: How polymorphism is implemented</h2>
<a name="polymorphism/implementation"></a>This section briefly describes how <a name="an2083"></a>
polymorphism is implemented in <strong>C++</strong>.
It is not necessary to understand how polymorphism is implemented if using
this feature is the only intention. However, we think it's nice to know how
polymorphism is at all possible. Besides, the following discussion does
explain why there is a cost of polymorphism in terms of memory usage.
<p>
The fundamental idea behind polymorphism is that the compiler does not know
which function to call <a name="an2084"></a>
compile-time; the appropriate function will be
selected <a name="an2085"></a>
run-time. That means that the <a name="an2086"></a>
 address of the
function must be stored somewhere, to be looked up prior to the actual
call. This `somewhere' place must be accessible from the object in
question. E.g., when a <code>Vehicle *vp</code> points to a <code>Truck</code> object, then
<code>vp-&gt;weight()</code> calls a member function of <code>Truck</code>; the address of this
function is determined from the actual object which <code>vp</code> points to.
<p>
A common implementation is the following: An object containing virtual member
functions holds as its <a name="an2087"></a>
first data member a <a name="an2088"></a>
 hidden
field, pointing to an array of pointers containing the addresses of the
virtual member functions. The hidden data member is usually called the
<a name="an2089"></a>
<em>vpointer</em>, the array of virtual member function addresses the <a name="an2090"></a>
<em>vtable</em>.
Note that the discussed implementation is compiler-dependent, and is by no
means dictated by the <strong>C++</strong> <a name="an2091"></a>
ANSI/ISO standard.
<p>
The table of addresses of virtual functions is shared by all objects of
the class. Multiple classes may even share  the same table. The
overhead in terms of <a name="an2092"></a>
memory consumption is therefore:
    <ul>
    <li> One extra pointer field per object, which points to:
    <li> One table of pointers per (derived) class storing the addresses of
the class's virtual functions.
    </ul>
    Consequently, a statement like <code>vp-&gt;weight()</code> first inspects the
hidden data member of the object pointed to by <code>vp</code>. In the case of the
vehicle classification system, this data member points to a table of two
addresses: one pointer for the function <code>weight()</code> and one pointer for
the function <code>setWeight()</code>. The actual function which is called is
determined from this table.
<p>
The internal organization of the objects having virtual functions is further
illustrated in figures Figure <a href="cplusplus14.html#ImplementationFigure">16</a> and Figure <a href="cplusplus14.html#CaumonFigure">17</a>
(provided by <a href="mailto:Guillaume.Caumon@ensg.inpl-nancy.fr">Guillaume
Caumon</a>).
<p>
<a name="ImplementationFigure"></a><p><center><img src="polymorphism/implementation.gif" align="bottom" alt="Figure 16 is shown here."/><br>
Figure 16: Internal organization objects when virtual functions are defined.
</center><p><br>

<p>
<a name="CaumonFigure"></a><p><center><img src="polymorphism/caumon.gif" align="bottom" alt="Figure 17 is shown here."/><br>
Figure 17: Complementary figure, provided by Guillaume Caumon
</center><p><br>

<p>
As can be seen from figures Figure <a href="cplusplus14.html#ImplementationFigure">16</a> and
Figure <a href="cplusplus14.html#CaumonFigure">17</a>, all objects which use virtual functions must have one
(hidden) data member to address a table of function pointers. The objects of
the classes <code>Vehicle</code> and <code>Auto</code> both address the same table. The class
<code>Truck</code>, however, introduces its own version of <code>weight()</code>: therefore,
this class needs its own table of function pointers.
<p>
<a name="l213"></a>
<h2>14.9: Undefined reference to vtable ...</h2>
<a name="polymorphism/undefined"></a>    Occasionaly, the linker will complain with a message like the following:
    <a name="an2093"></a>

    <a name="an2094"></a>

        <pre>
    In function
        `Derived::Derived[in-charge]()':
        : undefined reference to `vtable for Derived'
</pre>
    This error is caused by the absence of the implementation of
a virtual function in a derived class, while the function is mentioned in the
derived class's interface.
<p>
Such a situation can easily be created:
    <ul>
    <li> Construct a (complete) base class defining a virtual member function;
    <li> Construct a Derived class which mentions the virtual function in its
        interface;
    <li> The Derived class's virtual function, overriding the base class's
function having the same name, is not implemented. Of course, the compiler
doesn't know that the derived class's function is not implemented and will,
when asked, generate code to create a derived class object;
    <li> However, the linker is unable to find the derived class's virtual
member function. Therefore, it is unable to construct the derived class's
vtable;
    <li> The linker complains with the message:
        <pre>
    undefined reference to `vtable for Derived'
</pre>
    </ul>
    Here is an example producing the error:
        <pre>
    class Base
    {
        public:
            virtual void member();
    };

        inline void Base::member()
        {}

    class Derived
    {
        public:
            virtual void member();      // only declared
    };

    int main()
    {
        Derived d;  // Will compile, since all members were declared.
                    // Linking will fail, since we don't have the
                    // implementation of Derived::member()
    }
</pre>
    It's of course easy to correct the error: implement the derived class's
missing virtual member function.
<p>
<a name="VIRTCONS"></a><a name="l214"></a>
<h2>14.10: Virtual constructors</h2>
<a name="polymorphism/constructors"></a>As we have seen (section <a href="cplusplus14.html#VIRTDES">14.2</a>) <strong>C++</strong> supports <em>virtual
destructors</em>. Like many other object oriented languages (e.g., <strong>Java</strong>),
however, the notion of a <a name="an2095"></a>
<em>virtual constructor</em> is not supported. The
absence of a virtual constructor turns into a problem when only a base class
reference or pointer is available, and a copy of a derived class object is
required. <em>Gamma et al.</em> (1995) <a name="an2096"></a>
 developed the
    <a name="an2097"></a>
<em>Prototype Design Pattern</em> <a name="an2098"></a>

    to deal with this situation.
<p>
In the Prototype Design Pattern each derived class is given the
task to make available a member function returning a pointer to a new copy of
the object for which the member is called. The usual name for this function is
<code>clone()</code>. A base class supporting `cloning' only needs to define a virtual
destructor, and a <em>virtual copy constructor</em>, a pure virtual function,
having the prototype <code>virtual Base *clone() const = 0</code>.
<p>
Since <code>clone()</code> is a pure virtual function all derived classes must
implement their own `virtual constructor'.
<p>
This setup suffices in most situations where we have a pointer or
reference to a base class, but fails for example with abstract containers. We
can't create a <code>vector&lt;Base&gt;</code>, with <code>Base</code> featuring the pure virtual
<code>copy()</code> member in its interface, as <code>Base()</code> is called to initialize new
elements of such a vector. This is impossible as <code>clone()</code> is a pure virtual
function, so a <code>Base()</code> object can't be constructed.
<p>
The intuitive solution, providing <code>clone()</code> with a default
implementation, defining it as an ordinary virtual function, fails too as the
container calls the normal <code>Base(Base const &amp;)</code> copy constructor, which
would then have to call <code>clone()</code> to obtain a copy of the copy constructor's
argument. At this point it becomes unclear what to do with that copy, as the
new <code>Base</code> object already exists, and contains no <code>Base</code> pointer or
reference data member to assign <code>clone()</code>'s return value to.
<p>
An alternative and preferred approach is to keep the original <code>Base</code>
class (defined as an <a name="an2099"></a>
abstract base class), and to manage the <code>Base</code>
pointers returned by <code>clone()</code> in a separate class <code>Clonable()</code>. In
chapter <a href="cplusplus16.html#NESTEDCLASSES">16</a> we'll encounter means to merge <code>Base</code> and
<code>Clonable</code> into one class, but for now we'll define them as separate
classes.
<p>
The class <code>Clonable</code> is a very standard class. As it contains a pointer
member, it needs a copy constructor, destructor, and overloaded assignment
operator (cf. chapter <a href="cplusplus07.html#MEMORY">7</a>). It's given at least one non-standard
member: <code>Base &amp;get() const</code>, returning a reference to the derived object to
which <code>Clonable</code>'s <code>Base *</code> data member refers, and optionally a
<code>Clonable(Base const &amp;)</code> constructor to allow promotions from objects of
classes derived from <code>Base</code> to <code>Clonable</code>.
<p>
Any non-abstract class derived from <code>Base</code> must implement <code>Base
*clone()</code>, returning a pointer to a newly created (allocated) copy of the
object for which <code>clone()</code> is called.
<p>
Once we have defined a derived class (e.g., <code>Derived1</code>), we can put our
<code>Clonable</code> and <code>Base</code> facilities to good use.
<p>
In the next example we see <code>main()</code> in which a <code>vector&lt;Clonable&gt;</code> was
defined. An anonymous <code>Derived1</code> object is thereupon inserted into the
vector. This proceeds as follows:
    <ul>
    <li> The anonymous <code>Derived1</code> object is created;
    <li> It is promoted to <code>Clonable</code>, using <code>Clonable(Base const &amp;)</code>,
calling <code>Derived1::clone()</code>;
    <li> The just created <code>Clonable</code> object is inserted into the vector,
using <code>Clonable(Clonable const &amp;)</code>, again using <code>Derived1::clone()</code>.
    </ul>
    In this sequence, two temporary objects are used: the anonymous object and
the <code>Derived1</code> object constructed by the first <code>Derived1::clone()</code>
call. The third <code>Derived1</code> object is inserted into the vector. Having
inserted the object into the vector, the two temporary objects are destroyed.
<p>
Next, the <code>get()</code> member is used in combination with <code>typeid</code> to show
the actual type of the <code>Base &amp;</code> object: a <code>Derived1</code> object.
<p>
The most interesting part of main() is the line <code>vector&lt;Clonable&gt;
v2(bv)</code>, where a copy of the first vector is created. As shown, the copy keeps
intact the actual types of the <code>Base</code> references.
<p>
At the end of the program, we have created two <code>Derived1</code> objects, which
are then correctly deleted by the vector's destructors. Here is the full
program, illustrating the `virtual constructor' concept:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;vector&gt;
    #include &lt;typeinfo&gt;

    class Base
    {
        public:
            virtual ~Base();
            virtual Base *clone() const = 0;
    };

        inline Base::~Base()
        {}

    class Clonable
    {
        Base *d_bp;

        public:
            Clonable();
            ~Clonable();
            Clonable(Clonable const &amp;other);
            Clonable &amp;operator=(Clonable const &amp;other);

            // New for virtual constructions:
            Clonable(Base const &amp;bp);
            Base &amp;get() const;

        private:
            void copy(Clonable const &amp;other);
    };

        inline Clonable::Clonable()
        :
            d_bp(0)
        {}
        inline Clonable::~Clonable()
        {
            delete d_bp;
        }
        inline Clonable::Clonable(Clonable const &amp;other)
        {
            copy(other);
        }

        Clonable &amp;Clonable::operator=(Clonable const &amp;other)
        {
            if (this != &amp;other)
            {
                delete d_bp;
                copy(other);
            }
            return *this;
        }

        // New for virtual constructions:
        inline Clonable::Clonable(Base const &amp;bp)
        {
            d_bp = bp.clone();      // allows initialization from
        }                           // Base and derived objects
        inline Base &amp;Clonable::get() const
        {
            return *d_bp;
        }

        void Clonable::copy(Clonable const &amp;other)
        {
            if ((d_bp = other.d_bp))
                d_bp = d_bp-&gt;clone();
        }

    class Derived1: public Base
    {
        public:
            ~Derived1();
            virtual Base *clone() const;
    };

        inline Derived::~Derived1()
        {
            std::cout &lt;&lt; "~Derived1() called\n";
        }
        inline Base *Derived::clone() const
        {
            return new Derived1(*this);
        }

    using namespace std;

    int main()
    {
        vector&lt;Clonable&gt; bv;

        bv.push_back(Derived1());
        cout &lt;&lt; "==\n";

        cout &lt;&lt; typeid(bv[0].get()).name() &lt;&lt; endl;
        cout &lt;&lt; "==\n";

        vector&lt;Clonable&gt; v2(bv);
        cout &lt;&lt; typeid(v2[0].get()).name() &lt;&lt; endl;
        cout &lt;&lt; "==\n";
    }
</pre>
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus13.html">Previous Chapter</a>
    <li> <a href="cplusplus15.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
